package org.setamv.springcloud.resttemplate;

import org.springframework.beans.factory.SmartInitializingSingleton;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.web.client.RestTemplate;

import java.util.Collections;
import java.util.List;

@Configuration
public class MyRestTemplateConfiguration {

    /**
     * 注入声明了 {@linkplain MyLoadBalanced} 注解的Bean
     */
    @Autowired
    @MyLoadBalanced
    private List<RestTemplate> restTemplates = Collections.EMPTY_LIST;

    @Bean
    public SmartInitializingSingleton loadBalancerInitializing() {
        return new SmartInitializingSingleton() {
            @Override
            public void afterSingletonsInstantiated() {
                // 设置自定义拦截器，实现负载均衡
                MyLoadBalancerInterceptor myLoadBalancerInterceptor = new MyLoadBalancerInterceptor();
                for (RestTemplate restTemplate : restTemplates) {
                    // 将自定义的负载均衡拦截器设置到restTemplate中
                    List<ClientHttpRequestInterceptor> interceptors = restTemplate.getInterceptors();
                    interceptors.add(myLoadBalancerInterceptor);
                    restTemplate.setInterceptors(interceptors);
                }
            }
        };
    }
}
